<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\mongo\MongoOeVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class MongoVideoTagAllService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['mongo_video_tag_all'];

    /**
     * 更新低效视频素材.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getTagList(string $advertiserId = ''): bool
    {
        // 获取账户信息
        $obj = AccountService::getAccountModel(0, $advertiserId);
        if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
            return self::setError('账户数据不存在');
        }

        $page = 0;
        while (true) {
            $result = self::getList($advertiserId, ++$page);
            if ($result === false) {
                return false;
            }
            if (count($result['data']['materials']) == 0) {
                break;
            }
            foreach ($result['data']['materials'] as $item) {
                if (empty($item['material_id'])) {
                    continue;
                }

                $model = self::getInfo($advertiserId, strval($item['material_id']));
                if (! $model instanceof MongoOeVideoModel || ! $model->getKey()) {
                    continue;
                }
                if (empty($item['material_properties'])) {
                    $item['material_properties'] = [];
                }
                $model->setAttr('material_properties', $item['material_properties']);
                if (! $model->save()) {
                    self::setError('保存信息出错');
                }
            }
        }

        return true;
    }

    /**
     * 拉取信息.
     *
     * @return bool|mixed|string
     */
    private static function getList(string $advId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advId,
            'material_source' => 'AD',
            'page' => $page,
            'page_size' => OceanEnum::MAX_CUSTOM_MATERIAL_PAGE_SIZE,
        ];

        return AdvertiserService::getVideoTagList($headers, $params);
    }

    /**
     * 获取视频信息.
     *
     * @param string $advertiserId 账户id
     * @param string $materialId 素材id
     * @return null|array|mixed|Model|MongoOeVideoModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', string $materialId = '')
    {
        $where = [
            ['material_id', '=', $materialId],
            ['adv_id', '=', $advertiserId],
        ];

        return (new MongoOeVideoModel())->where($where)->field(true)->find();
    }
}
